package com.chuyu.cy.job;

import com.chuyu.cy.contants.Constant;
import com.chuyu.cy.entity.domain.User;
import com.chuyu.cy.exception.CustomException;
import com.chuyu.cy.service.UserService;
import com.chuyu.cy.utils.Common;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author: white-zhou
 * @date: 2024-06-16 18:42
 **/
@Component
public class AllUserToRedisJob {

    private final RedisTemplate<String, Object> redisTemplate;

    private final UserService userService;

    public AllUserToRedisJob(RedisTemplate<String, Object> redisTemplate, UserService userService) {
        this.redisTemplate = redisTemplate;
        this.userService = userService;
    }

    // 每12小时执行一次 0 0 0/12 * * ?
    @Scheduled(cron = "0 0 0/12 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void userToRedis() {
        long count = userService.count();
        try {
            redisTemplate.opsForValue().set(Constant.PROJECT_NAME + ":" + Constant.USER_COUNT,
                    count);
        } catch (Exception e) {
            throw new CustomException("redis存储失败");
        }
        if (count >= 2000) {
            if (Boolean.TRUE.equals(redisTemplate.hasKey(Constant.PROJECT_NAME + ":" + Constant.USER_LIST))) {
                redisTemplate.delete(Constant.PROJECT_NAME + ":" + Constant.USER_LIST);
                List<User> list = userService.list();
                List<User> safeUserList = Common.toSafeUserList(list);
                try {
                    redisTemplate.opsForList()
                            .leftPushAll(Constant.PROJECT_NAME + ":" + Constant.USER_LIST,
                                    safeUserList.toArray());
                } catch (Exception e) {
                    throw new CustomException("redis存储失败");
                }
            } else {
                List<User> list = userService.list();
                List<User> safeUserList = Common.toSafeUserList(list);
                try {
                    redisTemplate.opsForList()
                            .leftPushAll(Constant.PROJECT_NAME + ":" + Constant.USER_LIST,
                                    safeUserList.toArray());
                } catch (Exception e) {
                    throw new CustomException("redis存储失败");
                }
            }
        }
    }
}
